//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package impl

import (
	"context"

	"atomgit.com/openlinksaas-org/sql-proxy/gen_code"
)

type DatabaseApiImpl struct{}

func (s *DatabaseApiImpl) DatabaseListPost(ctx context.Context, req gen_code.DatabaseListPostRequest) (gen_code.ImplResponse, error) {
	if req.Token != token {
		return gen_code.ImplResponse{
			Code: 500,
			Body: gen_code.ErrInfo{
				ErrMsg: "wrong token",
			},
		}, nil
	}

	infoItem, ok := clientMap.Load(req.Id)
	if !ok {
		return gen_code.ImplResponse{
			Code: 500,
			Body: gen_code.ErrInfo{
				ErrMsg: "miss client",
			},
		}, nil
	}
	info := infoItem.(*ClientInfo)

	dbNameList := []string{}

	if info.Driver == "mysql" {
		rows, err := info.client.Query("SHOW DATABASES")
		if err != nil {
			return gen_code.ImplResponse{
				Code: 500,
				Body: gen_code.ErrInfo{
					ErrMsg: err.Error(),
				},
			}, nil
		}
		defer rows.Close()

		for rows.Next() {
			dbName := ""
			err = rows.Scan(&dbName)
			if err != nil {
				return gen_code.ImplResponse{
					Code: 500,
					Body: gen_code.ErrInfo{
						ErrMsg: err.Error(),
					},
				}, nil
			}
			dbNameList = append(dbNameList, dbName)
		}
	} else if info.Driver == "postgres" {
		rows, err := info.client.Query("SELECT datname FROM pg_database")
		if err != nil {
			return gen_code.ImplResponse{
				Code: 500,
				Body: gen_code.ErrInfo{
					ErrMsg: err.Error(),
				},
			}, nil
		}
		defer rows.Close()

		for rows.Next() {
			dbName := ""
			err = rows.Scan(&dbName)
			if err != nil {
				return gen_code.ImplResponse{
					Code: 500,
					Body: gen_code.ErrInfo{
						ErrMsg: err.Error(),
					},
				}, nil
			}
			if dbName == "postgres" || dbName == "template0" || dbName == "template1" {
				continue
			}
			dbNameList = append(dbNameList, dbName)
		}
	}
	return gen_code.ImplResponse{
		Code: 200,
		Body: dbNameList,
	}, nil
}
